package com.dlc.felear.xiaoensale.deviceControlSf;

import android.text.TextUtils;
import android.util.Log;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.factory.CmdList;
import com.dlc.felear.xiaoensale.utils.HexUtil;

public class MotorDiverControl {
    private static final String TAG = "MotorDiverControl";
    private int num;
    private String serialNum;
    private int lastLevel = -1;

    public MotorDiverControl(int num, String serialNum) {
        this.num = num;
        this.serialNum = serialNum;
        if(num==2){
            setSpeed(Constant.GT_DEFAULT_SPEED);
        }else {
            setSpeed(Constant.GT_DEFAULT_SPEED_1);
        }
    }

    public void setNum(int num){
        this.num = num;
    }

    /**
     * @param speed 1-17
     */
    public void setSpeed(int speed) {
        log("设置速度" + speed + " 当前速度:" + lastLevel);
        sendCmd(CmdList.setSfSpeend(num, speed));
        lastLevel = speed;
    }

    /**
     * 设置脉冲和转动方向
     *
     * @param dir
     * @param puls
     */
    public void setPuls(int dir, int puls) {
        log("脉冲数" + puls + " 方向:" + dir);
        sendCmd(CmdList.setSfOncePlus(num, dir, puls));
    }

    /**
     * 一直转
     *
     * @param dir
     */
    public void setAlwaysRun(int dir) {
        log("一直转 方向:" + dir);
        if (dir != 1) {
            dir = 2;
        }
        sendCmd(CmdList.setSfPlus(num, dir, 0));
    }

    /**
     * 0 减速 1不减速
     *
     * @param flag
     */

    public void stop(int flag) {
        log("停止-是否减速:" + flag);
        sendCmd(CmdList.setSfStop(num, flag));
    }

    /**
     * 发送指令
     *
     * @param data
     */
    private void sendCmd(byte[] data) {
//        log("serialNum=" + serialNum + " data=" + HexUtil.bytes2HexString(data));
        DlcSerialPortClient.getInstance().send(serialNum, data);
    }

    private void log(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            Log.e(TAG, "第" + num + "路电机:" + msg);
        }
    }
}
